const {  
  initExchangeFrom,   //将石油交易数量更新至缓存，同时扣除用户石油数量
  confirmExchange,    //确认交易
  getFinishExchangeInfo,    //获取交易完成相关信息
  cancelExchange,   //取消交易
  openExchange,   //打开交易所
  startExchange,    //我要交易
} = require('../lib/action');

module.exports = function (app) { return new Handler(app); };
let Handler = function (app) { this.app = app; };
let handler = Handler.prototype;

//打开交易所
handler.openExchange = async function (msg, session, next) {
  try{
    //打开交易所
    let info = await openExchange.call(this, session);
    next(null, {code: 200, info })
  }catch(err){
    next(err, {code: 500, msg: err.message});
  }
}

//我要交易
handler.startExchange = async function (msg, session, next) {
  let {house} = msg;
  try{
    let {oilNum, oilNumList} = await startExchange.call(this, session);
    //oilNum 可交易石油  oilNumList 交易数量列表 (交易所信息由客户端获取)
    next(null, {code: 200, oilNum, oilNumList});
  }catch(err){
    next(err, {code: 500, msg: err.message});
  }
}

//立即交易
handler.immediatelyExchange = async function(msg, session, next){
  let { num, house } = msg;    //num 客户选择的交易数量, house 客户选择的交易所
  try{
    //初始化表单
    await initExchangeFrom.call(this, session, num, house);
    next(null, {code: 200});
  }catch(err){
    next(err, {code: 500, msg: err.message});
  }
}

//交易完成
handler.finishExchange = async function (msg, session, next) {
  try{
    //获取交易相关信息
    let info = await getFinishExchangeInfo.call(this, session);
    //oilNum 交易数量  money 可得金额  tax 交易扣税  yesterdayPrice 昨日成交价
    next(null, {code: 200, ...info});
  }catch(err){
    next(err, {code: 500, msg: err.message});
  }
}

//确认交易
handler.confirmExchange = async function(msg, session, next){
  try{
    //确认交易
    await confirmExchange.call(this, session);
    next(null, {code: 200 });
  }catch(err){
    next(err, {code: 500, msg: err.message});
  }
}

//取消交易，扣除手续费，并更新内存数据
handler.cancelExchange = async function (msg, session, next) {
  try{
    //取消交易
    await cancelExchange.call(this, session);
    next(null, {code: 200 });
  }catch(err){
    next(err, {code: 500, msg: err.message});
  }
}
